<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片内容区域 -->
        <el-card class="box-card">
            <el-row :gutter="20">
                <el-col :span="7">
                    <!-- 搜索与添加 -->
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
                    <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
                    </el-input>
                </el-col>
                 <el-col :span="4">
                     <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
                 </el-col>
            </el-row>

            <!-- 用户列表区域 -->
            <el-table :data="userList" border stripe>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="姓名" prop="username"></el-table-column>
              <el-table-column label="邮箱" prop="email"></el-table-column>
              <el-table-column label="电话" prop="mobile"></el-table-column>
              <el-table-column label="角色" prop="role_name"></el-table-column>
              <el-table-column label="状态" width="100px" >
                <template slot-scope="scope" >
                 <el-switch
                    v-model="scope.row.mg_state"
                    @change="userstateChanged(scope.row)"
                    active-color="#13ce66"
                    inactive-color="#ff4949">
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <!-- 修改 -->
                  <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)" size="mini"></el-button>
                  <!-- 分配权限 -->
                  <el-tooltip  effect="dark" content="编辑权限" placement="top" :enterable="false">
                    <el-button type="warning" icon="el-icon-setting"  size="mini"></el-button>
                  </el-tooltip>
                  <!-- 删除 -->
                  <el-button type="danger" icon="el-icon-delete" @click="deleteUser(scope.row.id)" size="mini"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页导航 -->
            <el-pagination
              :current-page="queryInfo.pagenum"
              :page-size="queryInfo.pageSize"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :page-sizes="[1,3, 5, 10, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
        </el-card>

        <!-- 添加用户对话框 -->
        <el-dialog
          title="添加用户"
          :visible.sync="addUserDialogVisible"
          width="50%"
          @close="addDialogClosed"
        >
        <!-- 对话框内容主体区域 -->
          <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码"  prop="password">
              <el-input v-model="addForm.password" type="password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="addUserDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 修改用户对话框 -->
        <el-dialog
          title="修改用户"
          :visible.sync="editUserDialogVisible"
          width="50%"
          @close="editDialogClosed"
        >
        <!-- 对话框内容主体区域 -->
          <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
            <el-form-item label="用户名">
              <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="editUserDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUser()">确 定</el-button>
          </span>
        </el-dialog>

    </div>
</template>

<script>
export default {
  data () {
    return {
      userList: [],
      total: 0,
      // 添加用户对话框显示的控制变量
      addUserDialogVisible: false,
      // 修改用户对话框显示的控制变量
      editUserDialogVisible: false,
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },

      // 添加用户表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 8, max: 20, message: '长度在 8 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' }
        ]

      },
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
        id: 0
      }

    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败!')
      }
      this.userList = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    handleSizeChange (newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // switch开关状态监听
    async userstateChanged (userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('用户状态已更新')
    },
    // 添加用户对话框关闭监听重置表单
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },

    // 添加用户按钮单击事件
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
        } else {
          const { data: res } = await this.$http.post('users', this.addForm)
          if (res.meta.status !== 201) {
            this.$message.error('添加用户失败:' + res.meta.msg)
          } else {
            this.$message.success('添加用户成功！')
            // 重新获取用户数据
            this.getUserList()
            this.addUserDialogVisible = false
          }
        }
      })
    },

    // 展示编辑用户对话框
    showEditDialog (user) {
      console.log(user)
      this.editForm = user
      this.editUserDialogVisible = true
    },

    // 修改用户按钮单机事件监听
    editUser () {
      console.log('edit user')
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('修改用户信息失败')
        }
        const { data: res } = await this.$http.put('users/' + this.editForm.id,
          {
            email: this.editForm.username,
            mobile: this.editForm.mobile
          })
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户信息失败')
        }
        this.editUserDialogVisible = !this.editUserDialogVisible
        this.$message.success('修改用户信息成功')
        this.getUserList()
      })
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },

    // 删除用户按钮监听事件
    deleteUser (id) {
      console.log(id)
      this.$messageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // send delete info
        this.$http.delete('users/' + id).then(data => {
          if (data.data.meta.status !== 200) {
            this.$message.error('删除用户失败')
          } else {
            this.$message.success('删除用户成功')
            this.getUserList()
          }
        }).catch(error => {
          this.$message.error('删除用户失败')
          console.log(error)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>

</style>
